<template>
  <div style="width: 100%;height:100%">
    <h1>Zego RTC Video Call</h1>
    <div class="video-wrapper">
        <h4>Remote video</h4>
        <button @click="playByAC()">点击内存播放</button>
        <button @click="record()">{{ recording? '录音中...': '录音' }} 有3A</button>
        <!-- <button @click="recordNo3A()">{{ recording? '录音中...': '录音' }} 无3A</button> -->
        <hr>
        <!-- <video id="remote-video" autoplay playsinline controls></video> -->
        <div id="remote-view"></div>
    </div>
  </div>
  
</template>

<script>
import {ZegoExpressEngine} from 'zego-express-engine-webrtc'
import Vconsole from "vconsole";
import Recorder from 'js-audio-recorder';

export default {
  name: 'IosPlayAndRecord',
  props: {
    msg: String
  },
  data() {
    return {
      zg: null,
      appID: 1739272706,
      server: 'wss://webliveroom-test.zego.im/ws',
      userID: 'test_' + new Date().getTime(), // userID 用户自己设置，必须保证全局唯一
      userName: this.userID,// userName 用户自己设置，没有唯一性要求
      roomID: "7858", // roomID 用户自己设置，必须保证全局唯一
      effect: true,
      mixerDate: null, // 混流地址
      streamID: null,
      remoteStream: null,
      recorder: null,
      recording: false,
      remoteVideo: null,
      remoteView: null,

      recordStream: null,
    }
  },
  mounted() {
    this.init();
    new Vconsole();
  },
  methods: {
    init() {
      this.zg = new ZegoExpressEngine(this.appID, this.server);
      this.zg.setDebugVerbose(false);
      this.zg.setLogConfig({logLevel: 'disable'});
      window.zg = this.zg;
      this.zg.setSoundLevelDelegate(true, 1000);
      console.warn('recorder', this.recorder);
      navigator.getUserMedia =
          navigator.getUserMedia ||
          navigator.webkitGetUserMedia ||
          navigator.mozGetUserMedia;

      // this.zg.on('roomStateUpdate', async (roomID, state, errorCode, extendedData) => {
      //     console.warn(roomID, state, errorCode, extendedData);
      //     if(!errorCode) {
      //         if (state == 'CONNECTED') {
      //         }
      //     }
      // });
      zg.on('roomStreamUpdate', async (roomID, updateType, streamList, extendedData) => {
          console.warn('[roomStreamUpdate]', roomID, updateType, streamList, extendedData);
          if (updateType == 'ADD') {
              this.streamID = streamList[0].streamID;
              this.remoteStream = await this.zg.startPlayingStream(this.streamID);
              window.remoteStream = this.remoteStream;
              // this.remoteVideo = document.getElementById('remote-video');
              // this.remoteVideo.srcObject = this.remoteStream;
              this.remoteView = this.zg.createRemoteStreamView(this.remoteStream);
              // 将播放组件挂载到页面，"remote-video" 为组件容器 <div> 元素的 id 。
              this.remoteView.play("remote-view", {
                muted: true
              });
              // let ac = this.zg.zegoWebRTC.ac;
              // let src = ac.createMediaStreamSource(remoteStream);
              // src.connect(ac.destination);
              // ac.resume();

          }
      });
      
      fetch('https://sig-liveroom-admin.zego.cloud/thirdToken/get', {
          method: "POST",
          body: JSON.stringify({
              version: '04', 
              appId: this.appID,
              idName: this.userID,
              roomId: this.roomID,
              privilege: {
                  "1": 1,
                  "2": 1
              },
              expire_time: 100000000
          }),
          dataType: "json",
          contentType: "application/json; charset=utf-8"
      }).then(rsp=> rsp.json()).then(res=> {
          console.warn('[token]', res);
          const token = res.data.token
          // 登录
          this.zg.loginRoom(this.roomID, token, { userID: this.userID, userName: this.userName }, { userUpdate: true })
              .then(rsp=> console.warn('[登录 success]', rsp)).catch(err=> console.warn('[登录 fail]', err))
      });
    },
    playByAC() {
      let ac = this.zg.zegoWebRTC.ac;
      let src = ac.createMediaStreamSource(remoteStream);
      src.connect(ac.destination);
      ac.resume();
    },
    async record() {
      if(!this.recording) {
        this.recorder = new Recorder();
        this.recorder.start().then(() => {
            // 开始录音
            console.warn('[recorder.start()] success')
        }, (error) => {
            // 出错了
            console.warn(`[recorder.start()] error ${error.name} : ${error.message}`);
        });
        // this.recordStream = await navigator.mediaDevices.getUserMedia({video: false, audio: { 
        //   noiseSuppression: false,
        //   autoGainControl: false,
        //   echoCancellation: false
        // }});

      }else {
        this.recorder.destroy();
        // await this.zg.stopPlayingStream(this.streamID);
        
        // this.remoteStream = await this.zg.startPlayingStream(this.streamID);
        // this.remoteView = this.zg.createRemoteStreamView(this.remoteStream);
        // // 将播放组件挂载到页面，"remote-video" 为组件容器 <div> 元素的 id 。
        // this.remoteView.play("remote-view");
        // this.recordStream
        //   .getTracks()
        //   .reverse()
        //   .forEach(track => track.stop());
        // this.recordStream = null;
      }
      this.recording = !this.recording;
    },
    async recordNo3A() {
      if(!this.recording) {
        // this.recorder = new Recorder();
        // this.recorder.start().then(() => {
        //     // 开始录音
        //     console.warn('[recorder.start()] success')
        // }, (error) => {
        //     // 出错了
        //     console.warn(`[recorder.start()] error ${error.name} : ${error.message}`);
        // });
        this.recordStream = await navigator.mediaDevices.getUserMedia({video: false, audio: { 
          noiseSuppression: false,
          autoGainControl: false,
          echoCancellation: false
        }});

      }else {
        // this.recorder.destroy();
        // await this.zg.stopPlayingStream(this.streamID);
        
        // this.remoteStream = await this.zg.startPlayingStream(this.streamID);
        // this.remoteView = this.zg.createRemoteStreamView(this.remoteStream);
        // // 将播放组件挂载到页面，"remote-video" 为组件容器 <div> 元素的 id 。
        // this.remoteView.play("remote-view");
        this.recordStream
          .getTracks()
          .reverse()
          .forEach(track => track.stop());
        this.recordStream = null;
      }
      this.recording = !this.recording;
    }
  }
}
</script>
<style scoped>
button {
  width: 100%;
  height: 50px;
  display: inline-block;
}

</style>

<!-- Add "scoped" attribute to limit CSS to this component only -->
